package org.zwt.server;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.zwt.common.entity.HttpRequest;
import org.zwt.common.entity.HttpResponse;
import org.zwt.common.entity.ModelAndView;
import org.zwt.common.enumerate.RequestMethod;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@AllArgsConstructor
@NoArgsConstructor
@Data
public class ServiceThread implements Runnable {
    private Socket socket;
    private ServerConfig config;

    public ServiceThread(Socket socket) {
        this.socket = socket;
    }

    private boolean authenticateUser(String username, String password) {
        String url = "jdbc:mysql://localhost:3306/user_db";
        String user = "root";
        String dbPassword = "123456";
        String query = "SELECT * FROM users WHERE username = ? AND password = ?";

        try (Connection connection = DriverManager.getConnection(url, user, dbPassword);
                PreparedStatement preparedStatement = connection.prepareStatement(query)) {

            preparedStatement.setString(1, username);
            preparedStatement.setString(2, password);

            ResultSet resultSet = preparedStatement.executeQuery();
            return resultSet.next(); // Returns true if a record is found

        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public void run() {
        /*
         * 1.接收请求，解析成HttpRequest对象
         */
        InputStream is = null;
        HttpRequest httpRequest = null;
        try {
            is = this.socket.getInputStream();
            if (is.available() <= 0)
                return; // 结束执行
            httpRequest = this.config.getRequestHandler().handle(is);

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                this.socket.shutdownInput();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        /*
         * 2.检查请求中的URL路径和请求方法，使用对应的Java方法处理，并返回ModelAndView
         */
        if (httpRequest == null)
            return;

        ModelAndView mav = null;
        // 将login页面作为根页面
        if (httpRequest.getMethod() == RequestMethod.GET && httpRequest.getUrl().equals("/")) {
            mav = this.login();
        } else if (httpRequest.getMethod() == RequestMethod.GET && httpRequest.getUrl().equals("/index")) {
            mav = this.index();
        } else if (httpRequest.getMethod() == RequestMethod.GET && httpRequest.getUrl().equals("/home")) {
            mav = this.home();
        } else if (httpRequest.getMethod() == RequestMethod.POST && httpRequest.getUrl().equals("/login")) {
            String[] bodyParams = httpRequest.getBody().split("&");
            String username = null;
            String password = null;
            for (String param : bodyParams) {
                String[] keyValue = param.split("=");
                if (keyValue.length == 2) {
                    if ("username".equals(keyValue[0])) {
                        username = keyValue[1];
                    } else if ("password".equals(keyValue[0])) {
                        password = keyValue[1];
                    }
                }
            }

            if (username != null && password != null && authenticateUser(username, password)) {
                mav = this.index();
            } else {
                mav = this.login();
            }
        }
        /*
         * 3.将ModelAndView解析成响应对象HttpResponse
         */
        if (mav == null)
            return;
        HttpResponse response = null;
        try {
            response = this.config.getViewResolver().resolve(mav);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        /*
         * 4.格式化响应对象，并返回给客户端
         */
        if (response == null)
            return;
        OutputStream os = null;
        try {
            os = this.socket.getOutputStream();
            this.config.getResponseHandler().handle(response, os);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        /*
         * 5.关闭socket
         */
        try {
            this.socket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /*
     * 处理GET /index
     */
    public ModelAndView index() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("index");
        mav.setAttribute("name", "宗文涛");
        mav.setAttribute("age", "21");
        mav.setAttribute("school", "青岛农业大学海都学院");
        mav.setAttribute("major", "宗文涛");
        return mav;
    }

    /*
     * 处理GET /home
     */
    public ModelAndView home() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("home");
        mav.setAttribute("name", "宗文涛");
        mav.setAttribute("hobby", "编程,学习");
        mav.setAttribute("skills", "Java,JSP,springboot Python,爬虫, Web开发,小程序开发");
        mav.setAttribute("email", "zwt2395967300@163.com");
        mav.setAttribute("awards", "<br>强国杯三等奖<br>" +
                "软件杯二等奖<br>" +
                "山东省软件设计大赛一等奖<br>" +
                "山东省创客大赛一等奖<br>" +
                "山东省大学生移动互联大赛一等奖<br>" +
                "四级证书<br>" +
                "百度1+x证书");
        return mav;
    }

    /*
     * 处理GET /login
     */
    public ModelAndView login() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("login");
        return mav;
    }
}
